<?php
namespace App\Admin\Controllers\Chart;

use App\Exports\MaterialExport;
use App\Models\Material;
use App\Models\PurchaseToMaterial;
use Carbon\Carbon;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use Rap2hpoutre\FastExcel\Facades\FastExcel;
use Rap2hpoutre\FastExcel\SheetCollection;


class MaterialChartController
{
	public function index(Content $content, Request $request)
    {
    	$param = $request->all();

    	if(isset($param['dateTime'])) {
    	    $timeStart = Carbon::createFromFormat('Y', $param['dateTime']);
	        $timeEnd = Carbon::createFromFormat('Y', $param['dateTime']);
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }else {
    		$timeStart = new Carbon();
	        $timeEnd = new Carbon();
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }
    	//dd($timeBetween);
    	// x 轴为时间
	    $x = countX(12);
	    $data['进仓原材料'] = $this->Chart($x,$timeBetween, 1);
	    $data['出仓原材料'] = $this->Chart($x,$timeBetween, 2);
	    
	    $rgb = [
	    	"rgba(255,156,0,0.7)",
		    "rgba(3,162,156,0.7)",
	    ];
	    
	    $total = [
	        'purchase' => sumPurchase($data['进仓原材料']),
		    'outPut' => sumPurchase($data['出仓原材料']),
	    ];
	    
        return $content
	        ->header('仓库存货明细')
	        ->title('仓库存货明细')
	        //->row(view('admin.export.export-btn', ['route' => route('materialExport')]))
	        ->row(view('admin.chart.material.date-input'))
	        ->row(view('admin.chart.material.stock'))
	        //->row(view('admin.chart.material.total', ['total', $total]))
	        ->row(function (Row $row) use ($total){
	        	$row->column(3, view('admin.chart.material.total', compact('total')));
	        })
	        ->row(function (Row $row) use ($data, $x, $rgb){
				    $row->column(10, function (Column $column) use($data, $x, $rgb) {
				    	$column->row(view('admin.chart.material.purchase',
						    [
						    	'name' => '仓库存货明细',
							    'x' => $x,
							    'data' => $data,
							    'rgb' => $rgb
						    ]));
				    });
				});
    }
    
    public function post(Content $content, Request $request)
    {
        $param = $request->all();
		$timeStart = new Carbon($request->post('dateStart'));
    	$timeEnd = new Carbon($request->post('dateEnd'));
    	
    	// 查询信息
	    $data = $this->Chart([$timeStart, $timeEnd]);
    	$data = [];
    	return $content
	        ->header('仓库存货明细')
	        ->title('仓库存货明细')
	        ->row(view('admin.chart.material.input-form', ['material' => Material::all()->pluck('name', 'id')]))
	        ->row(function (Row $row) use ($data){
				    $row->column(10, function (Column $column) use($data) {
				    
				    });
				});
    }
    
    
    public function Chart($x, $timeBetween = [], $type = 1)
    {
        // x 轴为时间，12个月
	    
	        $data = PurchaseToMaterial::whereBetween('created_at', $timeBetween)
			    ->whereHas('recordmaterial', function (Builder $query) use($type){
			        $query->where('type', $type);// 1采购2消耗
			    })
			    ->selectRaw('Month(created_at) as date, sum(unit_price * number) as value')
			    ->groupBy('date')
			    ->get();

    	foreach ($x as $k => $v)
	    {
			$y[$v] = [
				'x' => $v,
				'value' => 0
			];
	    	foreach ($data as $key => $value)
		    {
		        	if($value->date == $v){
		        	    $y[$v]['value'] = $value->value / 100;
			        }
		    }
	    }
    	return $y;
    }
    
    public function export(Request $request)
    {
        $time = new Carbon();
        
        $validate = Validator::make($request->all(), [
        	'dateTime' => 'numeric'
        ]);
        if($validate->failed()){
            return false;
        }
        
        if(isset($dateTime)) {
    	    $timeStart = Carbon::createFromFormat('Y', $dateTime);
	        $timeEnd = Carbon::createFromFormat('Y', $dateTime);
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }else {
    		$timeStart = new Carbon();
	        $timeEnd = new Carbon();
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }
        // 调用laravel excel
	    return Excel::download(new MaterialExport($timeBetween), '材料'.$request->get('dateTime').'年.xlsx');
        $data = $this->exportData($request->get('dateTime'));
        
        return FastExcel::data($data)->download('材料'.$request->get('dateTime').'年.xlsx');
    }
    
    public function exportData($dateTime)
    {
        $timeStart = new Carbon();
    	$timeEnd = new Carbon();
    	
    	if(isset($dateTime)) {
    	    $timeStart = Carbon::createFromFormat('Y', $dateTime);
	        $timeEnd = Carbon::createFromFormat('Y', $dateTime);
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }else {
    		$timeStart = new Carbon();
	        $timeEnd = new Carbon();
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }
    	
    	$dataI = PurchaseToMaterial::whereBetween('created_at', $timeBetween)
			    ->whereHas('recordmaterial', function (Builder $query){
			        $query->where('type', 1);// 1采购2消耗
			    })
			    ->selectRaw('Month(created_at) as 月份, sum(unit_price * number) as 金额')
			    ->groupBy('月份')
			    ->get();
    	$dataO = PurchaseToMaterial::whereBetween('created_at', $timeBetween)
			    ->whereHas('recordmaterial', function (Builder $query){
			        $query->where('type', 2);// 1采购2消耗
			    })
			    ->selectRaw('Month(created_at) as 月份, sum(unit_price * number) as 金额')
			    ->groupBy('月份')
			    ->get();
    	
    	$list = new SheetCollection([
    		'材料进货' => recordOrderChart($dataI),
		    '生成商品' => recordOrderChart($dataO)
	    ]);
    	
    	return $list;
    }
    
    public function stockExport(Request $request)
    {
    	$time = new Carbon();
        
        $validate = Validator::make($request->all(), [
        	'dateTime' => 'numeric'
        ]);
        if($validate->failed()){
            return false;
        }
        
        if(isset($dateTime)) {
    	    $timeStart = Carbon::createFromFormat('Y', $dateTime);
	        $timeEnd = Carbon::createFromFormat('Y', $dateTime);
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }else {
    		$timeStart = new Carbon();
	        $timeEnd = new Carbon();
	        $timeBetween = [$timeStart->startOfYear(), $timeEnd->endOfYear()];
	    }
        // 调用laravel excel
	    return Excel::download(new MaterialExport($timeBetween), '材料'.$request->get('dateTime').'年.xlsx');
    }
}